package org.ssp.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.ssp.base.GetRandomString;
import org.ssp.dao.UserDao;
import org.ssp.impl.UserImpl;
import org.ssp.pojo.Travel;
import org.ssp.pojo.User;
import org.ssp.test.CustomerService;
import org.ssp.pojo.BaseMessage;
import org.ssp.pojo.Music;
import org.ssp.pojo.MusicMessage;
import org.ssp.pojo.NewsMessage;
import org.ssp.pojo.TextMessage;
import org.ssp.pojo.Token;
import org.ssp.util.CommonUtil;
import org.ssp.util.KFSessionUtil;
import org.ssp.util.GetUuid;
import org.ssp.util.MenuUtil;
import org.ssp.util.MessageUtil;
import org.ssp.util.MySqlUtil;

import net.sf.json.JSONObject;

public class CoreService {
	private static Logger logger=Logger.getLogger(CoreService.class);
	public static final String AppID="wx33b73bd6220f28a4";//oec
	public static final String AppSecret="9dd210874cd63ff055a1edcf48e8c53a";
    public static final String BaseUrl="http://creatgo.com";

	public static String processRequest(HashMap<String, String>requestMap){
		System.out.println("....processquest.........");
		//遍历hashmap
	   Iterator iter = requestMap.entrySet().iterator();
	   while(iter.hasNext()){
		   Map.Entry<String, String> entry=(Map.Entry<String, String>)iter.next();
		   String key=entry.getKey();
		   String value=entry.getValue();
		   System.out.println(key+"="+value);
	   }
		//创建响应消息对象
		TextMessage tm=new TextMessage();
		String respxml=null;

		try {
			//解析微信服务器发送的请求
//			HashMap<String,String> requestMap=MessageUtil.parseXML(request);
			//用户的openid
			String fromUserName=requestMap.get("FromUserName");
			//公众号的原始id
			String toUserName=requestMap.get("ToUserName");
			//请求消息类型
			String msgType=requestMap.get("MsgType");
			logger.info(String.format("用户的openid：%s,消息类型:%s",fromUserName,msgType));
			tm.setFromUserName(toUserName);
			tm.setToUserName(fromUserName);
			tm.setMsgType(MessageUtil.RES_MESSAGE_TYPE_TEXT);
			tm.setCreateTime(new Date().getTime());
			
			//判断，不同消息的处理及返回xml
			if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)){
				String content=requestMap.get("Content");
				//回复2048字节内容
				if("1".equals(content)){
					BaseMessage mesg=new BaseMessage();
					mesg.setFromUserName(toUserName);
					mesg.setToUserName(fromUserName);
					mesg.setCreateTime(new Date().getTime());
					mesg.setMsgType(MessageUtil.RES_MESSAGE_TYPE_TRANSFER);
				    respxml=MessageUtil.messageToXML(mesg);
				}
		
				if("5".equals(content)){
					tm.setContent("xoxo");
					respxml=MessageUtil.messageToXML(tm);
				}
				if(content.equals("/::D")){
					tm.setContent("怎么这么高兴?[疑问]/疑问/:?");
					respxml=MessageUtil.messageToXML(tm);
				}
				
				
				if("music".equals(content)){
				
					Music music=new Music();
					music.setTitle("旅行");
					music.setDescription("许巍");
					music.setMusicUrl("http://mytestapp.ngrok.natapp.cn/weixin-02/music/lvxing.mp3");
					music.setHQMusicUrl("http://mytestapp.ngrok.natapp.cn/weixin-02/music/lvxing.mp3");
					
					MusicMessage mmsg=new MusicMessage();
					mmsg.setFromUserName(toUserName);
					mmsg.setToUserName(fromUserName);
					mmsg.setMsgType(MessageUtil.RES_MESSAGE_TYPE_MUSIC);
					mmsg.setCreateTime(new Date().getTime());
					mmsg.setMusic(music);
					respxml=MessageUtil.messageToXML(mmsg);
					
					
				}
				//回复 单图文消息(不含图片)
				if("6".equals(content)){
					logger.info("用户输入6");
					//创建图文对象
					Travel article=new Travel();
					article.setTitle("博客");
					//将图文添加到集合
					List<Travel> articleList=new ArrayList<Travel>();
					articleList.add(article);
					
					//创建图文消息
					NewsMessage nmsg=new NewsMessage();
					nmsg.setToUserName(fromUserName);
					nmsg.setFromUserName(toUserName);
					nmsg.setCreateTime(new Date().getTime());
					nmsg.setMsgType(MessageUtil.RES_MESSAGE_TYPE_NEWS);
					nmsg.setArticleCount(articleList.size());
				    nmsg.setArticles(articleList);
				    respxml=MessageUtil.messageToXML(nmsg);
				    logger.info(respxml);
				    					
				}
				//回复单图文消息
				if("7".equals(content)){
					//创建图文对象
					Travel article=new Travel();
					article.setTitle("博客");
//					article.setDescription("技术博客--博客园");
//					article.setPicUrl("http://mytestapp.ngrok.natapp.cn/weixin-02/image/1.jpg");
//					article.setUrl("http://www.cnblogs.com/web-coding/");
//					
					//将图文添加到集合
					List<Travel> articleList=new ArrayList<Travel>();
					articleList.add(article);
					//创建图文消息
					NewsMessage nmsg=new NewsMessage();
					nmsg.setToUserName(fromUserName);
					nmsg.setFromUserName(toUserName);
					nmsg.setCreateTime(new Date().getTime());
					nmsg.setMsgType(MessageUtil.RES_MESSAGE_TYPE_NEWS);
					nmsg.setArticleCount(articleList.size());
				    nmsg.setArticles(articleList);
				    respxml=MessageUtil.messageToXML(nmsg);
				}
				//回复多图文消息
				if("8".equals(content)){
					//创建图文对象
					Travel article1=new Travel();
					article1.setTitle("博客");
//					article1.setDescription("技术博客--博客园");
//					article1.setPicUrl("http://mytestapp.ngrok.natapp.cn/weixin-02/image/1.jpg");
//					article1.setUrl("http://www.cnblogs.com/web-coding/");
					
					Travel article2=new Travel();
					article2.setTitle("博客");
//					article2.setDescription("技术博客--博客园");
//					article2.setPicUrl("http://mytestapp.ngrok.natapp.cn/weixin-02/image/1.jpg");
//					article2.setUrl("http://www.cnblogs.com/web-coding/");
					
					Travel article3=new Travel();
					article3.setTitle("博客");
//					article3.setDescription("技术博客--博客园");
//					article3.setPicUrl("http://mytestapp.ngrok.natapp.cn/weixin-02/image/1.jpg");
//					article3.setUrl("http://www.cnblogs.com/web-coding/");
					
					//将图文添加到集合
					List<Travel> articleList=new ArrayList<Travel>();
					articleList.add(article1);
					articleList.add(article2);
					articleList.add(article3);

					
					//创建图文消息
					NewsMessage nmsg=new NewsMessage();
					nmsg.setToUserName(fromUserName);
					nmsg.setFromUserName(toUserName);
					nmsg.setCreateTime(new Date().getTime());
					nmsg.setMsgType(MessageUtil.RES_MESSAGE_TYPE_NEWS);
					nmsg.setArticleCount(articleList.size());
				    nmsg.setArticles(articleList);
				    respxml=MessageUtil.messageToXML(nmsg);
				}
				
				if("9".equals(content)){
					//获取access_token
					Token token = CommonUtil.getAccessToken("wxf34da76143f5050d", "7a6df503a9afaa70601d652cfb99b16d");
					System.out.println(token.getAccessToken());
					String json=MenuUtil.objectToJson();
					MenuUtil.createMenu(json, token.getAccessToken());
					
				}
				//用户发送的是自行车
				if("自行车".equals(content)){
					tm.setContent("这辆"+MessageUtil.emoji(0x1F6B2)+"怎么样，好看吧？");		
					respxml=MessageUtil.messageToXML(tm);
				}
				if(content.equals("签到")){
					boolean result=MySqlUtil.isTodaySigned(fromUserName);
					if(result){
						tm.setContent("您今天已经签到过");
					}else{
						boolean flag=MySqlUtil.isSevenSign(fromUserName, MySqlUtil.getMondayOfThisWeek()+" 00:00:00");
						//连续7天签到，送12积分
						if(flag){
							MySqlUtil.saveWeixinSign(fromUserName, 2);
							MySqlUtil.updateUserPoints(fromUserName, 12);
							tm.setContent("签到成功，获得2个积分！\n本周连续签到7次，额外赠送10个积分");
						}
						//每次送2个
						else{
							//需要做一个判断，当weixin_sign已经存在时，不需要创建表格指令
							String sql="create table weixin_sign("+
						               "id int(11) not null auto_increment primary key,"+
									   "open_id varchar(100),"+
						               "sign_time datetime,"+
						               "sign_points int(11)"+
									   ")";
							MySqlUtil.createTable(sql);
							MySqlUtil.saveWeixinSign(fromUserName, 2);
							MySqlUtil.updateUserPoints(fromUserName, 2);
							tm.setContent("签到成功，得到2个积分");
							
						}
					}
					respxml=MessageUtil.messageToXML(tm);
				}
			}else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)){
//				System.out.println("接受到的图片地址是;"+requestMap.get("PicUrl"));
//				String json=facePlusPlusUtil.detectFace(requestMap.get("PicUrl"));
//				tm.setContent(facePlusPlusUtil.jsonToText(json));
////				tm.setContent("您发送的是图片信息");
//				respxml=MessageUtil.messageToXML(tm);
			

			}else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)){
				System.out.println("进入音频log");
				tm.setContent("您发送的是音频信息");
				
			}else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VIDEO)){
				System.out.println("进入视频log");
				tm.setContent("您发送的是视频信息");
				
			}else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)){
				tm.setContent("您发送的是地址信息");
				
			}else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)){
				tm.setContent("您发送的是链接信息");				
			}else if(msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)){
				logger.info("事件");
				//事件类型
				String eventType=requestMap.get("Event");
				String eventKey=requestMap.get("EventKey");
				logger.info(eventType);
				logger.info(eventKey);
				if(eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)){
	                   if(eventKey==null||"".equals(eventKey)){
	                	   System.out.println(".......subscribe");
	                	   //查数据库，判断是否已经绑定，返回不同的授权url
						/*	UserDao userdao=new UserImpl();						
							StringBuffer strbf=new StringBuffer();
							if(userdao.findByOpenId(fromUserName)==null){
								String str1="进行账号绑定:";
								strbf.append(str1);
								String str2="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf34da76143f5050d&redirect_uri=http%3a%2f%2f33ac248d.ngrok.natapp.cn%2foec%2flogin?method=wxpage&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
								String url="<a href='"+str2+"'>点击绑定</a>";
								strbf.append(url);
							}else{
								String str1="您已经进行过绑定了";
								strbf.append(str1);
								String str2="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf34da76143f5050d&redirect_uri=http%3a%2f%2f163177c3.ngrok.natapp.cn%2foec%2fpage1.jsp&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
								String url="<a href='"+str2+"'>点击登录</a>";
								strbf.append(url);
							}*/
//							tm.setContent("oec留学欢迎您！"+strbf.toString());	
	                	   tm.setContent("oec留学欢迎您!");
							respxml=MessageUtil.messageToXML(tm);
	                   }/*else{//扫码带参数二维码未关注
	                	    System.out.println("......suscribe+123.....");
	                		UserDao userdao=new UserImpl();	
							User user=userdao.findByOpenId(fromUserName);
							if(user==null){
								user=new User();
								String uid=GetUuid.getUid();
								String pwd=GetRandomString.getRandomString(8);
								user.setUid(uid);
								user.setPassword(pwd);
								user.setOpenid(fromUserName);
								UserDao userd=new UserImpl();
								userd.addUser2(user);
							}
							tm.setFromUserName(toUserName);
							tm.setToUserName(fromUserName);
							tm.setCreateTime(new Date().getTime());
							tm.setMsgType(MessageUtil.RES_MESSAGE_TYPE_TEXT);
							tm.setContent("您已成功创建oec账号。账户"+user.getUid()+";密码"+user.getPassword());
							respxml=MessageUtil.messageToXML(tm);
	                   }*/
					
				}/*else if(eventType.equals("SCAN")){//扫码带参数二维码已经关注过
					 System.out.println("......suscribe+123.....");
             		 UserDao userdao=new UserImpl();	
						User user=userdao.findByOpenId(fromUserName);
						if(user==null){
							user=new User();
							String uid=GetUuid.getUid();
							String pwd=GetRandomString.getRandomString(8);
							user.setUid(uid);
							user.setPassword(pwd);
							user.setOpenid(fromUserName);
							UserDao userd=new UserImpl();
							userd.addUser2(user);
						}
						tm.setFromUserName(toUserName);
						tm.setToUserName(fromUserName);
						tm.setCreateTime(new Date().getTime());
						tm.setMsgType(MessageUtil.RES_MESSAGE_TYPE_TEXT);
						tm.setContent("您已成功创建oec账号。账户"+user.getUid()+";密码"+user.getPassword());
						respxml=MessageUtil.messageToXML(tm);
				}*/else if(eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)){
					logger.info("取消关注");
					//更新weixin_user表和weixin_sign表信息
//					MySqlUtil.deleteRecords();
					
				}else if(eventType.equals(MessageUtil.EVENT_TYPE_CLICK)){//菜单点击事件
					if(eventKey.equals("KEY_JIAOSHUI")){
						StringBuffer sbf = new StringBuffer();
						sbf.append("大学城校区送水电话：\n")
						   .append("东区送水短号：664130\n")
						   .append("西区送水短号：618404 \n");
						tm.setContent(sbf.toString());
						respxml=MessageUtil.messageToXML(tm);
					}else if(eventKey.equals("KEY_CONSULT")){//开启多客服
//						Token token=CommonUtil.getAccessToken(CoreService.AppID, CoreService.AppSecret);
//						String result=KFSessionUtil.userSessionStatus(token.getAccessToken(),  fromUserName);
//						JSONObject json=JSONObject.fromObject(result);
//						if(json.getString("kf_account").trim()!=null){
//							tm.setFromUserName(toUserName);
//							tm.setToUserName(fromUserName);
//							tm.setCreateTime(new Date().getTime());
//							tm.setMsgType(MessageUtil.RES_MESSAGE_TYPE_TRANSFER);
//							tm.setContent("当前已经是 客服模式，可以直接咨询客服人员");
//						}else{
							BaseMessage mesg=new BaseMessage();
							mesg.setFromUserName(toUserName);
							mesg.setToUserName(fromUserName);
							mesg.setCreateTime(new Date().getTime());
							mesg.setMsgType(MessageUtil.RES_MESSAGE_TYPE_TRANSFER);
						    respxml=MessageUtil.messageToXML(mesg);
//						}
					}
				}/*else if(eventType.equals("kf_close_session")){//关闭会话事件
					tm.setFromUserName(toUserName);
					tm.setToUserName(fromUserName);
					tm.setCreateTime(new Date().getTime());
					tm.setMsgType(MessageUtil.RES_MESSAGE_TYPE_TRANSFER);
					tm.setContent("[退出客服模式]");
					respxml=MessageUtil.messageToXML(tm);
				}*/
			}			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return respxml;
	}
	

}
